#!coding=utf-8
import os
import re
from functools import cmp_to_key
import shutil


def compare(file_name1, file_name2):
    """
    比较2个文件的文件名，并返回比较结果
    :param name1:
    :param name2:
    :return:
    """

    # 中文数字映射
    chinese_numerals = {'零': 0, '一': 1, '二': 2, '两': 2, '三': 3, '四': 4,
                        '五': 5, '六': 6, '七': 7, '八': 8, '九': 9}
    unit_map = {'十': 10, '百': 100, '千': 1000, '万': 10000, '亿': 100000000}

    # 将中文数字字符串转换为阿拉伯数字
    def chinese_to_arabic(chinese_number):
        if not chinese_number:
            return 0

        result = 0
        first_unit = chinese_number[0] in unit_map
        num = 0
        for index, char in enumerate(chinese_number):
            if char in chinese_numerals:
                num = chinese_numerals[char]
                if index == len(chinese_number) - 1:
                    result += num
            elif char in unit_map:
                if index == 0 and first_unit:
                    result += unit_map[char]
                else:
                    result += num * unit_map[char]
                num = 0
        return result


    filename_num1 = re.findall(r"第(.+)章", file_name1)[0]
    filename_num2 = re.findall(r"第(.+)章", file_name2)[0]


    filename_num1_int = chinese_to_arabic(filename_num1)
    filename_num2_int = chinese_to_arabic(filename_num2)

    if filename_num1_int > filename_num2_int:
        return 1
    elif filename_num1_int < filename_num2_int:
        return -1
    else:
        return 0

def merge_text_files(file_list, output_file):
    with open(output_file, 'wb') as outfile:
        for file in file_list:
            with open(file, 'rb') as infile:
                shutil.copyfileobj(infile, outfile)

def main():
    files = os.listdir(r"小说")
    sorted_files = sorted(files, key=cmp_to_key(compare))
    file_list = [os.path.join(r"小说", file) for file in sorted_files]
    merge_text_files(file_list, '阴脉先生')

if __name__ == '__main__':
    main()